package com.kgc.provider;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.kgc.api.user.FootPrintApi;
import com.kgc.api.user.LoginApi;
import com.kgc.api.user.UserInfoApi;
import com.kgc.bean.Footprint;
import com.kgc.bean.User;
import com.kgc.config.WechatAuthConfig;
import com.kgc.util.RedisUtils;
import com.kgc.util.ResultBuildUtil;
import com.kgc.util.ReturnResult;
import com.kgc.util.Sample;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

/**
 * @Classname loginProvider
 * @Description TODO
 * @Date 2021/6/21 9:39
 * @Created by 17402
 */
@Service
@Slf4j
public class LoginProvider implements LoginApi {
    @Autowired
    private UserProvider userProvider;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private WechatAuthConfig wechatAuthConfig;
    @Autowired
    private FootPrintApi footPrintApi;
    @Autowired
    private UserInfoApi userApi;
    @Override
    public ReturnResult<Map<String, Object>> sendCode(String phone) {
        Map<String,Object> sendCodeReturnData=new HashMap<>();
        Random random = new Random();
        int code = random.nextInt(10000);
        while (code < 1000) {
            code = random.nextInt(10000);
        }
        Sample.smsSign(phone, code);
        //验证码要存在Redis里面
        if(redisUtils.set(phone,code,600)){
            sendCodeReturnData.put("msg","验证码发送成功！");
        }else {
            return ResultBuildUtil.fail("1001","验证码发送失败!");
        }

        return ResultBuildUtil.success(sendCodeReturnData);
    }

    @Override
    public ReturnResult<Map<String, Object>> userCode2loginOrRegistered(String phone, String code, List<String> goodIdList) {
        Map<String,Object> logInOrRegisteredReturnData=new HashMap<>();
        log.info("code:{}",code);
        log.info("redisCode:{}",redisUtils.get(phone));
        //判断手机号是否存在， 存在直接登录成功，不存在就注册成功
        if(null==redisUtils.get(phone)){
            return ResultBuildUtil.fail("1002","----（你的验证码可能失效了，请重新获取）！---");
        }
        if(code.equals(redisUtils.get(phone).toString())){
            log.info("-----userProvider.phoneIsUsed(phone):{}---",userProvider.phoneIsUsed(phone));
            if(userProvider.phoneIsUsed(phone)){
                logInOrRegisteredReturnData.put("msg","登录成功");
                //判断会员是否过期，过期重置vip状态
                User user=userProvider.selectUserByPhone(phone);
                Date date=new Date();
                if(user.getVipEndTime()==null||user.getVipEndTime().before(date)){
                    user.setIsvip(0);
                    userApi.modifyUserInformation(user);
                }
                //登录成功将用户存到Redis
                String token= UUID.randomUUID().toString();
                redisUtils.set(token, JSON.toJSONString(userProvider.selectUserByPhone(phone)),24*60*60*3);
                logInOrRegisteredReturnData.put("token",token);
                redisUtils.del(phone);
            }else {
                logInOrRegisteredReturnData.put("msg","注册成功！");
                //注册成功将用户存到Redis 并且存到用户表
                User user=new User();
                user.setUsername(phone);
                user.setPhone(phone);
                user.setIsvip(0);
                String token=UUID.randomUUID().toString();
                userProvider.addUser(user);
                user.setUserId(userProvider.selectUserByPhone(phone).getUserId());
                log.info("……………………………………………………userInfo:{}………………………………………………………………",JSON.toJSONString(user));
                redisUtils.set(token, JSON.toJSONString(user),24*60*60*3);
                logInOrRegisteredReturnData.put("token",token);

                redisUtils.del(phone);
            }
            //将cookie中的足迹存入数据库
            User finalUser = userProvider.selectUserByPhone(phone);
            Collections.reverse(goodIdList);
            if(goodIdList!=null&&goodIdList.size()>0){
                goodIdList.forEach(goodId->{
                    if(null==footPrintApi.findFootprint(goodId,finalUser.getUserId())){
                        Footprint footprint=new Footprint();
                        footprint.setUserId(finalUser.getUserId());
                        footprint.setFootprintGoodsId(goodId);
                        footprint.setFootprintTime(new Date());
                        footPrintApi.addFootPrint(footprint);
                    }else {
                        //
                        Footprint footprint=footPrintApi.findFootprint(goodId,finalUser.getUserId());
                        footprint.setFootprintTime(new Date());
                        footPrintApi.updateFootTime(footprint);
                    }
                });
            }
        }else {

            return ResultBuildUtil.fail("1003","验证码不正确");
        }

        return ResultBuildUtil.success(logInOrRegisteredReturnData);

    }

    @Override
    public ReturnResult<Map<String, Object>> getWxLoginQRCode() {
        Map<String,Object> getWxLoginQRCodeReturnData=new HashMap<>();
        // 封装获取code的请求地址
        log.info("++++++weChatAuthConfig:{}+++++++++",wechatAuthConfig.toString());
        log.info("^^^^^^^weChatAuthConfig.getCodeUri():{}^^^^^^^^^^",wechatAuthConfig.getCodeUri());
        StringBuffer sbf = new StringBuffer(wechatAuthConfig.getCodeUri());
        // 官方请求案例
        sbf.append("?appid=").append(wechatAuthConfig.getAppId())
                .append("&redirect_uri=").append(wechatAuthConfig.getRedirectUri())
                .append("&response_type=code")
                .append("&scope=snsapi_userinfo")
                .append("&state=STATE#wechat_redirect");
        // 请求url
        log.info("获取code的请求地址：{}", sbf.toString());
        getWxLoginQRCodeReturnData.put("sbf",sbf);
        return ResultBuildUtil.success(getWxLoginQRCodeReturnData);

    }
}
